
import java.util.*;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author David Beaver
 */
public class FtpServer implements Runnable{
    private ServerSocket ftpServer;
    private ServerConfig config;
    private Integer port;
    private ThreadPool pool;
    
    public FtpServer(Integer port, ServerConfig config){
        try {
            this.port = port;
            this.ftpServer = new ServerSocket(this.port);
            this.config = config;
            this.pool = new ThreadPool(this.config.getMaxThreads()/2);
            System.out.println("FTP: Listening for file requests...");
        } catch (IOException ex) {
            System.err.println("Error creating ftp server");
        }
    } 
    
    public void run() {
        while(true){
            try {
                //block until another request is found
                FtpHandler ftpRequest = new FtpHandler(this.ftpServer.accept(), this.config); //build handler
                System.out.println("\nFTP: Incoming command!!");
                this.pool.assign(new Thread(ftpRequest)); //start the handler
            } catch (IOException ex) {
                Logger.getLogger(FtpServer.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
    }
}
